<?php

namespace Summer\Box\Http\Controllers;

use Illuminate\Routing\Controller;
use RLuders\JWTAuth\Classes\JWTAuth;
use Summer\Box\Models\BoxItemModel;

use Summer\Box\Models\Settings as BoxSettings;
use Summer\Hub\Http\Controllers\Traits\ApiReturn;
use Input;
use Config;
use Db;
use Carbon\Carbon;

class ItemController extends Controller
{
    use ApiReturn;

    /**
     * 交易大厅
     */
    public function index(JWTAuth $auth)
    {
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        $page_size=Input::get('page_size')??20;
        $page=Input::get('page')??1;

        //获取结束倒计时
        $slug=Input::get('slug');
        if(empty($slug)){
            return $this->apiError('缺少场次参数');
        }
        if(!in_array($slug,[1,2,3])){
            return $this->apiError('场次参数错误');
        }
        $box_settings= BoxSettings::instance();
        $sessions=$box_settings->sessions;
        $sessions_arr=[];
        foreach ($sessions as $sv){
            $sessions_arr[$sv['slug']]=$sv;
        }
        $begin_time=$sessions_arr[$slug]['begin_time'];
        $end_time=$sessions_arr[$slug]['end_time'];
        $today_date_str=Carbon::today()->toDateString();
        $begin_time_str=$today_date_str." ".$begin_time;
        $end_time_str=$today_date_str." ".$end_time;
        $begin = new Carbon($begin_time_str);
        $end = new Carbon($end_time_str);
        $now=Carbon::now();
        $beginint = $now->diffInSeconds($begin, false); // $int 为正负数
        $endint = $now->diffInSeconds($end, false); // $int 为正负数


        if(!$now->between($begin,$end)){
            $records=[];
        }else{
            $query=BoxItemModel::select();
            $query->where('user_id','<>',$user->id);
            if(in_array($slug,[1,2])){
                $query->where('type',$slug);
            }
            $query->where('status',1);
//        $query->where('is_shangjia',1);
            $query->inRandomOrder();
            $records=$query->paginate($page_size,$page);
            $records->each(function ($record){
                $record->cover=url('/storage/app/media'.$record->cover);
            });
        }

        $rdata['records']=$records;
        $rdata['beginint']=$beginint;
        $rdata['endint']=$endint;
        return $this->apiSuccess('操作成功',$rdata);

    }


}
